package com.sl.au.service.impl;


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sl.au.entity.Contract;
import com.sl.au.entity.ContractInfo;
import com.sl.au.entity.ContractPart;
import com.sl.au.entity.ContractPump;
import com.sl.au.entity.ContractRepair;
import com.sl.au.entity.ExdeTbOPPlanTask;
import com.sl.au.entity.ExdeTbOPPlanTaskDetail;
import com.sl.au.entity.ExdeTbOPPlanTaskDetailReplace;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.User;
import com.sl.au.repository.ExdeSchedulingRepository;
import com.sl.au.repository.ExdeTbOPPlanTaskDetailReplaceRepository;
import com.sl.au.repository.ExdeTbOPPlanTaskDetailRepository;
import com.sl.au.service.ContractService;
import com.sl.au.service.DocService;
import com.sl.au.service.ExdeSchedulingService;
import com.sl.utils.DataConverter;


@Service("ExdeSchedulingService")
@Transactional
public class ExdeSchedulingServiceImpl extends BaseServiceImpl implements ExdeSchedulingService {

	@Autowired
	ExdeSchedulingRepository exdeSchedulingRepository;

	@Autowired
	ExdeTbOPPlanTaskDetailRepository exdeTbOPPlanTaskDetailRepository;

	@Autowired
	ExdeTbOPPlanTaskDetailReplaceRepository exdeTbOPPlanTaskDetailReplaceRepository;

	@Autowired
	ContractService contractService;
	
	@Override
	public ExdeSchedulingRepository getExdeSchedulingRepository() {
		return this.exdeSchedulingRepository;
	}

	@Override
	public List<ExdeTbOPPlanTask> getContractInfos(int start, int length, Map<String, String> condition,
			String orderName, String dir) {
		Page<ExdeTbOPPlanTask> pages = null;
		String dataFilter = condition.get("dataFilter");
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "dCreateDate");
		if(dataFilter.equals("所有")){
			pages = exdeSchedulingRepository.getContractInfos(condition.get("key"), condition.get("state"), pageable);
		}else if(dataFilter.equals("本部门")){
			pages = exdeSchedulingRepository.getContractInfos(condition.get("key"), condition.get("superior"), condition.get("state"), pageable);
		}else if(dataFilter.equals("本片区")){
			pages = exdeSchedulingRepository.getContractInfos(condition.get("key"), condition.get("superior"), condition.get("areaName"), condition.get("state"),  pageable);
		}else if(dataFilter.equals("本人")){
			pages = exdeSchedulingRepository.getContractInfosByUser(condition.get("key"), condition.get("userId"), condition.get("state"), pageable);
		}
		return pages.getContent();
	}

	@Override
	public long getContractInfosCount(Map<String, String> condition) {
		String dataFilter = condition.get("dataFilter");
		if(dataFilter.equals("所有")){
			return this.exdeSchedulingRepository.getContractInfoCount(condition.get("key"),  condition.get("state"));
		}else if(dataFilter.equals("本部门")){
			return this.exdeSchedulingRepository.getContractInfoCount(condition.get("key"), condition.get("superior"),  condition.get("state"));
		}else if(dataFilter.equals("本片区")){
			return this.exdeSchedulingRepository.getContractInfoCount(condition.get("key"), condition.get("superior"), condition.get("areaName"),  condition.get("state"));
		}else{
			return this.exdeSchedulingRepository.getContractInfoByUserCount(condition.get("key"), condition.get("userId"),  condition.get("state"));
		}
	}

	@Override
	public String getPlanNumber() {
		Date date=new Date();
		String code=DataConverter.toDateYMD(date);
		String PlanNumber="PN"+code;
		long count=exdeSchedulingRepository.getCodeCount(PlanNumber);
		if(count+1<10) PlanNumber=PlanNumber+"000"+(count+1);
		else if(count+1>=10&&count+1<100) PlanNumber=PlanNumber+"00"+(count+1);
		else if(count+1>=100&&count+1<1000) PlanNumber=PlanNumber+"0"+(count+1);
		else PlanNumber=PlanNumber+(count+1);
		return PlanNumber;
	}

	@Override
	public ExdeTbOPPlanTaskDetailRepository getExdeTbOPPlanTaskDetailRepository() {
		return this.exdeTbOPPlanTaskDetailRepository;
	}

	@Override
	public ExdeTbOPPlanTaskDetailReplaceRepository getExdeTbOPPlanTaskDetailReplaceRepository() {
		return this.exdeTbOPPlanTaskDetailReplaceRepository;
	}

	@Override
	public int saveExdeTbOPPlanTask(String[] ids, User user) {
		int result = 0;
		boolean t = true;
		for (String id : ids){
			ContractInfo old = contractService.getRepository().getDateThreeContractById(id);
			long quoteDevices = contractService.getDevicesCount(id);
			long quoteReplacements = contractService.getReplacementsCount(id);
			if(quoteDevices==0 && quoteReplacements==0) {
				result = 0;
				t=false;
			}else{
				//if(old.getOpPlanTaskId()==null) System.out.println(old.getOpPlanTaskId());
				//if(old.getOpPlanTaskId().equals("")) System.out.println(2);
				//if(old.getCstate() == null) System.out.println(4);
				//if(old.getCstate().equals("未排产")) System.out.println(3);
				//if(old.getCstate()=="") System.out.println(5);
				if(!(old.getOpPlanTaskId()==null && (old.getCstate() == null || old.getCstate().equals("未排产") || old.getCstate()==""))){
					result = 1;
					t=false;
				}
			}
		}
		if(t){
			for (String id : ids){
				ContractInfo old = contractService.getRepository().getDateThreeContractById(id);
				List<QuoteDevice> quoteDevices = contractService.getDevices(0, Integer.MAX_VALUE, id, null, null);
				List<QuoteReplacement> quoteReplacements = contractService.getReplacements(0, Integer.MAX_VALUE, id, null, null);
				if(quoteDevices.size()>0||quoteReplacements.size()>0){
					String type = old.getContractType();
					String ContractId = old.getContractId();
					String PlanTaskId = "";
					//if(old.getOpPlanTaskId()==null && (old.getCstate() =="未排产" || old.getCstate() == null || old.getCstate()=="")) 
						PlanTaskId = java.util.UUID.randomUUID().toString();
					//else return result=1;//选中合同中有已经生成过计划任务的数据
					//if(quoteDevices.size()==0&&quoteReplacements.size()==0) return result=0; //合同录入细目不完整！
					ExdeTbOPPlanTask exdeTbOPPlanTask = new ExdeTbOPPlanTask();
					exdeTbOPPlanTask.setId(PlanTaskId);
					exdeTbOPPlanTask.setcPlanNumber(this.getPlanNumber());
					exdeTbOPPlanTask.setdOrderDate(old.getSignedDate());//订货日期
					exdeTbOPPlanTask.setdDeliveryDate(old.getGiveOutDate());//交货日期
					if(old.getDemanderCode()!=null&&!old.getDemanderCode().equals("")){
						exdeTbOPPlanTask.setcContractNumber(old.getSupplierCode()+"/"+old.getDemanderCode());//供方合同号
					}else{
						exdeTbOPPlanTask.setcContractNumber(old.getSupplierCode());//供方合同号
					}
					exdeTbOPPlanTask.setDemanderCode(old.getDemanderCode());//需方合同编号
					exdeTbOPPlanTask.setContractInfo(old);//合同ID
					exdeTbOPPlanTask.setContractType(old.getContractType());
					exdeTbOPPlanTask.setcUserUnit(old.getOrderUnit());//订货单位
					exdeTbOPPlanTask.setnUserUnitId(old.getCustomerId());//订货单位ID
					exdeTbOPPlanTask.setnContractManager(old.getSignOfficer());//合同签订人
					//exdeTbOPPlanTask.setcType("成套");
					exdeTbOPPlanTask.setcState("新增");
					exdeTbOPPlanTask.setcIsGenerated("未生成");//商品计划
					exdeTbOPPlanTask.setUser(user);//创建人
					exdeTbOPPlanTask.setUsername(user.getName());//创建人
					exdeTbOPPlanTask.setdCreateDate(new Date());//创建时间
					exdeTbOPPlanTask.setcCreateDept(user.getSaleArea().getSuperior());//创建部门
					exdeTbOPPlanTask.setAreaName(user.getSaleArea().getAreaName());//创建片区
					exdeSchedulingRepository.save(exdeTbOPPlanTask);
					if(quoteDevices.size()>0){
						for(QuoteDevice quoteDevice : quoteDevices){
							ExdeTbOPPlanTaskDetail exdeTbOPPlanTaskDetail = new ExdeTbOPPlanTaskDetail();
							exdeTbOPPlanTaskDetail.setId(quoteDevice.getId());
							exdeTbOPPlanTaskDetail.setUser(user);
							exdeTbOPPlanTaskDetail.setcCreateUser(user.getName());
							exdeTbOPPlanTaskDetail.setcCreateDept(user.getSaleArea().getSuperior());
							exdeTbOPPlanTaskDetail.setOpPlanTaskId(PlanTaskId);
							exdeTbOPPlanTaskDetail.setcProductModel(quoteDevice.getProductModel());
							exdeTbOPPlanTaskDetail.setcProductType(quoteDevice.getProductType());
							exdeTbOPPlanTaskDetail.setnSinglePrice(quoteDevice.getUnitPrice());
							exdeTbOPPlanTaskDetail.setnCount(quoteDevice.getNumber());
							exdeTbOPPlanTaskDetail.setnTotalPrice((double)(quoteDevice.getNumber()*quoteDevice.getUnitPrice()));
							exdeTbOPPlanTaskDetail.setcAdditionClaim(quoteDevice.getcAttachment());//附加要求
							exdeTbOPPlanTaskDetail.setnContractProductId(old.getContractId());
							exdeTbOPPlanTaskDetail.setcMotor(quoteDevice.getcMotor());
							exdeTbOPPlanTaskDetail.setcPower(quoteDevice.getPower());
							exdeTbOPPlanTaskDetail.setcBitNumber(quoteDevice.getcBitNumber());
							//exdeTbOPPlanTaskDetail.setcUnit(quoteDevice.getcUnit());
							exdeTbOPPlanTaskDetail.setcFlow(quoteDevice.getFlux());
							exdeTbOPPlanTaskDetail.setcHead(quoteDevice.getPumpLift());
							exdeTbOPPlanTaskDetail.setcTemperature(quoteDevice.getTemperature());
							exdeTbOPPlanTaskDetail.setcViscosity(quoteDevice.getViscosity());
							exdeTbOPPlanTaskDetail.setcProportion(quoteDevice.getProportion());
							exdeTbOPPlanTaskDetail.setcInletPressure(quoteDevice.getInPressure());
							exdeTbOPPlanTaskDetail.setcOutletPressure(quoteDevice.getcOutletPressure());
							exdeTbOPPlanTaskDetail.setcMaterialFlow(quoteDevice.getFlowMaterial());
							exdeTbOPPlanTaskDetail.setcNPSHa(quoteDevice.getEffectiveNPSHA());
							exdeTbOPPlanTaskDetail.setcNPSHr(quoteDevice.getMustMPSHA());
							exdeTbOPPlanTaskDetail.setcProductName(quoteDevice.getProductName());
							exdeTbOPPlanTaskDetail.setdGiveDate(quoteDevice.getdDeliveryDate()==null ? old.getGiveOutDate() : quoteDevice.getdDeliveryDate());
							exdeTbOPPlanTaskDetail.setdOrderDate(old.getSignedDate());
							exdeTbOPPlanTaskDetail.setcTransMedium(quoteDevice.getTransMedia());
							exdeTbOPPlanTaskDetailRepository.save(exdeTbOPPlanTaskDetail);
						}
					}
					if(quoteDevices.size()==0&&quoteReplacements.size()>0){
						ExdeTbOPPlanTaskDetail exdeTbOPPlanTaskDetail = new ExdeTbOPPlanTaskDetail();
						exdeTbOPPlanTaskDetail.setId(java.util.UUID.randomUUID().toString());
						exdeTbOPPlanTaskDetail.setUser(user);
						exdeTbOPPlanTaskDetail.setcCreateUser(user.getName());
						exdeTbOPPlanTaskDetail.setcCreateDept(user.getSaleArea().getSuperior());
						exdeTbOPPlanTaskDetail.setOpPlanTaskId(PlanTaskId);
						exdeTbOPPlanTaskDetail.setcProductModel("备件");
						exdeTbOPPlanTaskDetail.setcProductType("备件");
						exdeTbOPPlanTaskDetail.setnSinglePrice((float)old.getTotalSum());
						exdeTbOPPlanTaskDetail.setnCount(1);
						exdeTbOPPlanTaskDetail.setnTotalPrice(old.getTotalSum());
						//exdeTbOPPlanTaskDetail.setcAdditionClaim(quoteDevice);附加要求
						exdeTbOPPlanTaskDetail.setnContractProductId(old.getContractId());
						exdeTbOPPlanTaskDetail.setcProductName("备件");
						exdeTbOPPlanTaskDetail.setdGiveDate(old.getGiveOutDate());
						//exdeTbOPPlanTaskDetail.setCreateTime(new Date());
						exdeTbOPPlanTaskDetail.setdGiveDate(old.getGiveOutDate());
						exdeTbOPPlanTaskDetail.setdOrderDate(old.getSignedDate());
						exdeTbOPPlanTaskDetailRepository.save(exdeTbOPPlanTaskDetail);
					}
					if(quoteReplacements.size()>0){
						for(QuoteReplacement quoteReplacement : quoteReplacements){
							ExdeTbOPPlanTaskDetailReplace ExdeTbOPPlanTaskDetailReplace = new ExdeTbOPPlanTaskDetailReplace();
							ExdeTbOPPlanTaskDetailReplace.setOpPlanTaskId(PlanTaskId);
							ExdeTbOPPlanTaskDetailReplace.setContractID(quoteReplacement.getContractID());
							ExdeTbOPPlanTaskDetailReplace.setContractType(quoteReplacement.getContractType());
							ExdeTbOPPlanTaskDetailReplace.setSupplierCode(quoteReplacement.getSupplierCode());
							ExdeTbOPPlanTaskDetailReplace.setDeviceName(quoteReplacement.getDeviceName());
							ExdeTbOPPlanTaskDetailReplace.setAmount(quoteReplacement.getAmount());
							ExdeTbOPPlanTaskDetailReplace.setMaterial(quoteReplacement.getMaterial());
							ExdeTbOPPlanTaskDetailReplace.setUnit(quoteReplacement.getUnit());
							ExdeTbOPPlanTaskDetailReplace.setPrice(quoteReplacement.getCostPrice());
							ExdeTbOPPlanTaskDetailReplace.setCostPrice(quoteReplacement.getCostPrice());
							ExdeTbOPPlanTaskDetailReplace.setDiscount(quoteReplacement.getDiscount());
							ExdeTbOPPlanTaskDetailReplace.setnOneDiscount(quoteReplacement.getnOneDiscount());
							ExdeTbOPPlanTaskDetailReplace.setType(quoteReplacement.getType());
							ExdeTbOPPlanTaskDetailReplace.setHostType(quoteReplacement.getHostType());
							ExdeTbOPPlanTaskDetailReplace.setMemo(quoteReplacement.getMemo());
							ExdeTbOPPlanTaskDetailReplace.setCreateTime(new Date());
							ExdeTbOPPlanTaskDetailReplace.setdGiveDate(old.getGiveOutDate());
							ExdeTbOPPlanTaskDetailReplace.setdOrderDate(old.getSignedDate());
							ExdeTbOPPlanTaskDetailReplace.setMaterialCoding(quoteReplacement.getMaterialCoding());
							exdeTbOPPlanTaskDetailReplaceRepository.save(ExdeTbOPPlanTaskDetailReplace);
						}
					}
					if (type.equals("项目合同")){
						Contract oldOne = contractService.getRepository().findOne(ContractId);
						if (oldOne!=null){
							oldOne.setOpPlanTaskId(PlanTaskId);
							oldOne.setCstate("已排产");
							oldOne.setScheduleDate(new Date());
							contractService.getRepository().save(oldOne);
							result=2;
						}
					}else if (type.equals("备件合同")){
						ContractPart oldOne = contractService.getRepository2().findOne(ContractId);
						if (oldOne!=null){
							oldOne.setOpPlanTaskId(PlanTaskId);
							oldOne.setCstate("已排产");
							oldOne.setScheduleDate(new Date());
							contractService.getRepository2().save(oldOne);
							result=2;
						}
					}else if (type.equals("备泵合同")){
						ContractPump oldOne = contractService.getRepository3().findOne(ContractId);
						if (oldOne!=null){
							oldOne.setOpPlanTaskId(PlanTaskId);
							oldOne.setCstate("已排产");
							oldOne.setScheduleDate(new Date());
							contractService.getRepository3().save(oldOne);
							result=2;
						}
					}else if (type.equals("维修合同")){
						ContractRepair oldOne = contractService.getRepository4().findOne(ContractId);
						if (oldOne!=null){
							oldOne.setOpPlanTaskId(PlanTaskId);
							oldOne.setCstate("已排产");
							oldOne.setScheduleDate(new Date());
							contractService.getRepository4().save(oldOne);
							result=2;
						}
					}
					
				}
				else return result = 0;
			}
		}
		return result;
	}

	@Override
	public List<ExdeTbOPPlanTaskDetail> getPlanTaskDetail(int start, int length, String id, String orderName,
			String dir) {
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		return exdeSchedulingRepository.getPlanTaskDetail(id, pageable);
	}

	@Override
	public List<ExdeTbOPPlanTaskDetailReplace> getPlanTaskDetailReplace(int start, int length, String id,
			String orderName, String dir) {
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.ASC, "id");
		return exdeSchedulingRepository.getPlanTaskDetailReplace(id, pageable);
	}

	@Override
	public long getPlanTaskDetailCount(int i, int maxValue, String id, String orderName, String dir) {
		return exdeSchedulingRepository.getPlanTaskDetailCount(id);
	}

	@Override
	public long getPlanTaskDetailReplaceCount(int i, int maxValue, String id, String orderName, String dir) {
		return exdeSchedulingRepository.getPlanTaskDetailReplaceCount(id);
	}

	@Override
	public int regainPlanTask(String[] ids, User user) {
		int result = 0;
		for (String id : ids){
			ExdeTbOPPlanTask old = exdeSchedulingRepository.findOne(id);
			if(old==null) return result=1;
			if(old != null&&old.getUser().getId().toString().equals(user.getId().toString()) && old.getcState().equals("下达")){
				old.setcState("新增");
				old.setdIssuedDate(null);
				exdeSchedulingRepository.save(old);
				result = 0;
			}else return result = 2;
		}
		return result;
	}
	@Override
	public int deletePlanTask(String[] ids, User user) {
		int result = 0;
		boolean t = true;
		for (String id : ids){
			ExdeTbOPPlanTask old = exdeSchedulingRepository.findOne(id);
			if(!(old.getUser().getId().toString().equals(user.getId().toString()) && old.getcState().equals("新增"))){
				result = 1;
				t=false;
			}
			if(old == null){
				result = 2;
				t=false;
			}
		}
		if(t){
			for (String id : ids){
				ExdeTbOPPlanTask old = exdeSchedulingRepository.findOne(id);
				if(old!=null && old.getUser().getId().toString().equals(user.getId().toString()) && old.getcState().equals("新增")){
					List<ExdeTbOPPlanTaskDetail> details = exdeTbOPPlanTaskDetailRepository.findByopPlanTaskId(old.getId());
					List<ExdeTbOPPlanTaskDetailReplace> replaces = exdeTbOPPlanTaskDetailReplaceRepository.findByPlanTaskId(old.getId());
					if(details.size()>0){
						for(ExdeTbOPPlanTaskDetail detail : details)
							exdeTbOPPlanTaskDetailRepository.delete(detail);
					}
					if(replaces.size()>0){
						for(ExdeTbOPPlanTaskDetailReplace replace : replaces)
							exdeTbOPPlanTaskDetailReplaceRepository.delete(replace);
					}
					String type = old.getContractInfo().getContractType();
					String ContractId = old.getContractInfo().getContractId();
					if (type.equals("项目合同")){
						Contract oldOne = contractService.getRepository().findOne(ContractId);
						if (oldOne!=null){
							oldOne.setOpPlanTaskId(null);
							oldOne.setCstate("未排产");
							contractService.getRepository().save(oldOne);
						}
					}else if (type.equals("备件合同")){
						ContractPart oldOne = contractService.getRepository2().findOne(ContractId);
						if (oldOne!=null){
							oldOne.setOpPlanTaskId(null);
							oldOne.setCstate("未排产");
							contractService.getRepository2().save(oldOne);
						}
					}else if (type.equals("备泵合同")){
						ContractPump oldOne = contractService.getRepository3().findOne(ContractId);
						if (oldOne!=null){
							oldOne.setOpPlanTaskId(null);
							oldOne.setCstate("未排产");
							contractService.getRepository3().save(oldOne);
						}
					}else if (type.equals("维修合同")){
						ContractRepair oldOne = contractService.getRepository4().findOne(ContractId);
						if (oldOne!=null){
							oldOne.setOpPlanTaskId(null);
							oldOne.setCstate("未排产");
							contractService.getRepository4().save(oldOne);
						}
					}
					exdeSchedulingRepository.delete(old);
					result = 0;
				}
			}
		}else return result;
		return result;
	}

	@Override
	public String genQuoteDocx(String id, String sender) {
		String filename = null;
		ExdeTbOPPlanTask exdeTbOPPlanTask = exdeSchedulingRepository.findOne(id);
		DecimalFormat df = new DecimalFormat( "###############0.00 ");
		Double sum = 0.0;
		if (null != exdeTbOPPlanTask) {
			Map<String, Object> data = new HashMap<>();
			Map<String, LinkedList<List<String>>> tablesData = new HashMap<>();
			List<ExdeTbOPPlanTaskDetail> details = exdeTbOPPlanTaskDetailRepository.findByopPlanTaskId(id);
			LinkedList<List<String>> linkeddetails1 = new LinkedList<>();
			List<String> row1;
			int order1 = 0;
			for (ExdeTbOPPlanTaskDetail detail : details) {
				row1 = new ArrayList<>();
				row1.add((++order1) + "");
				row1.add(detail.getcProductName());
				row1.add(detail.getcProductModel());
				row1.add(detail.getcBitNumber());
				row1.add(detail.getcTransMedium());
				row1.add(detail.getcTemperature());
				row1.add(detail.getcMotor());
				row1.add(detail.getcPower());
				row1.add("");
				row1.add(detail.getcAdditionClaim());
				row1.add(detail.getnCount() + "");
				row1.add(df.format(detail.getnTotalPrice()) + "");
				sum += detail.getnTotalPrice();
				linkeddetails1.add(row1);
			}
			tablesData.put("q", linkeddetails1);
			Map<String, String> textData = new HashMap<>();
			textData.put("sum", String.format("%.2f", sum).toString());
			textData.put("customerName", exdeTbOPPlanTask.getcContractNumber());
			textData.put("cUserUnit",exdeTbOPPlanTask.getcUserUnit());
			textData.put("nContractManager",exdeTbOPPlanTask.getnContractManager());
			textData.put("dDeliveryDate",DataConverter.toZnDateYMD(exdeTbOPPlanTask.getdDeliveryDate()));
			
			textData.put("a", exdeTbOPPlanTask.getnViolationDeliveryDate()==1?"是":"否");
			textData.put("b", exdeTbOPPlanTask.getnVPerformance()==1?"是":"否");
			textData.put("c", exdeTbOPPlanTask.getnVQuality()==1?"是":"否");
			textData.put("d", exdeTbOPPlanTask.getnVOther());
			
			textData.put("e", exdeTbOPPlanTask.getnBPBase()==1?"是":"否");
			textData.put("f", exdeTbOPPlanTask.getdBaseDate()==null?"":DataConverter.toDateYMD(exdeTbOPPlanTask.getdBaseDate()));
			textData.put("g", exdeTbOPPlanTask.getnBPInterface()==1?"是":"否");
			textData.put("h", exdeTbOPPlanTask.getdInterfaceDate()==null?"":DataConverter.toDateYMD(exdeTbOPPlanTask.getdInterfaceDate()));
			textData.put("i", exdeTbOPPlanTask.getnBPPID()==1?"是":"否");
			textData.put("j", exdeTbOPPlanTask.getdPIDDate()==null?"":DataConverter.toDateYMD(exdeTbOPPlanTask.getdPIDDate()));
			textData.put("k", exdeTbOPPlanTask.getnBPElectricity()==1?"是":"否");
			textData.put("l", exdeTbOPPlanTask.getdElectricityDate()==null?"":DataConverter.toDateYMD(exdeTbOPPlanTask.getdElectricityDate()));
			textData.put("m", exdeTbOPPlanTask.getnBPWiring()==1?"是":"否");
			textData.put("n", exdeTbOPPlanTask.getdWiringDate()==null?"":DataConverter.toDateYMD(exdeTbOPPlanTask.getdWiringDate()));
			textData.put("o", exdeTbOPPlanTask.getnBPControlCubicle()==1?"是":"否");
			textData.put("p", exdeTbOPPlanTask.getdControlCubicleDate()==null?"":DataConverter.toDateYMD(exdeTbOPPlanTask.getdControlCubicleDate()));
			textData.put("q", exdeTbOPPlanTask.getnTestReport()==1?"是":"否");
			textData.put("r", exdeTbOPPlanTask.getdTestReportDate()==null?"":DataConverter.toDateYMD(exdeTbOPPlanTask.getdTestReportDate()));
			textData.put("s", exdeTbOPPlanTask.getnBPOther());
			
			textData.put("t", exdeTbOPPlanTask.getnExJail()==1?"是":"否");
			textData.put("u", exdeTbOPPlanTask.getnExThirdParty()==1?"是":"否");
			textData.put("v", exdeTbOPPlanTask.getnExLeav()==1?"是":"否");
			textData.put("w", exdeTbOPPlanTask.getnPaintCompany()==1?"是":"否");
			textData.put("x", exdeTbOPPlanTask.getnPaintUser()==1?"是":"否");
			textData.put("y", exdeTbOPPlanTask.getnPackingOrdinary()==1?"是":"否");
			textData.put("z", exdeTbOPPlanTask.getnPackingExport()==1?"是":"否");
			textData.put("aa", exdeTbOPPlanTask.getnPackingUser()==1?"是":"否");
			
			textData.put("bb", exdeTbOPPlanTask.getcOtherRequirement());
			
			textData.put("cCreateDept", exdeTbOPPlanTask.getcCreateDept());
			textData.put("userName", exdeTbOPPlanTask.getUser().getEmpLogin().getName());
			textData.put("dCreateDate", DataConverter.toZnDateYMD(exdeTbOPPlanTask.getdCreateDate()));
			textData.put("guaranteeMonths", "24");
			data.put("textData", textData);
			data.put("tablesData", tablesData);
			filename = DocService.genTemplate("订货合同计划任务单.docx", data, "订货合同计划任务单");
			exdeTbOPPlanTask.setnPrintCount(exdeTbOPPlanTask.getnPrintCount()+1);
			exdeTbOPPlanTask.setnPrintDate(new Date());
		}
		return filename;
	}

	/**
	 * 下达
	 */
	@Override
	public int issuedplan(String[] ids, User user) {
		int result = 0;
		for (String id : ids){
			ExdeTbOPPlanTask old = exdeSchedulingRepository.findOne(id);
			if(old == null){
				result = 1;
			}
			if(old != null&&old.getUser().getId().toString().equals(user.getId().toString())&& old.getcState().equals("新增")){
				old.setcState("下达");
				old.setdIssuedDate(new Date());
				exdeSchedulingRepository.save(old);
				result = 0;
			}else result = 2;
		}
		return result;
	}

	@Override
	public String genBJScheduling(String id, User user) {
		String filename = null;
		DecimalFormat df = new DecimalFormat( "###############0.00 ");
		ExdeTbOPPlanTask exdeTbOPPlanTask = exdeSchedulingRepository.findOne(id);
		if (null != exdeTbOPPlanTask) {
			Map<String, Object> data = new HashMap<>();
			Map<String, LinkedList<List<String>>> tablesData = new HashMap<>();
			List<ExdeTbOPPlanTaskDetailReplace> details = exdeTbOPPlanTaskDetailReplaceRepository.findByPlanTaskId(id);
			ContractInfo contractInfo = exdeTbOPPlanTask.getContractInfo();
			LinkedList<List<String>> linkeddetails1 = new LinkedList<>();
			Double sum = 0.0;
			Integer number = 0;
			List<String> row1;
			int order1 = 0;
			if(contractInfo.getSuperior().equals("成套处")){
				for (ExdeTbOPPlanTaskDetailReplace detail : details) {
					row1 = new ArrayList<>();
					row1.add((++order1) + "");
					row1.add(detail.getDeviceName());
					row1.add(detail.getType());
					row1.add(detail.getUnit());
					row1.add(detail.getAmount()+"");
					row1.add((detail.getnOneDiscount()==null? df.format(0):df.format(detail.getnOneDiscount())) + "");//detail.getDiscount()+
					row1.add(detail.getMaterialCoding());
					//row1.add(df.format(detail.getnOneDiscount())+"");
					//row1.add(df.format(detail.getAmount()*detail.getnOneDiscount())+"");
					
					//row1.add(df.format(detail.getnOneDiscount())+"");
					//row1.add(df.format(detail.getPrice())+"");
					row1.add(detail.getMemo());
					number += detail.getAmount();
					sum += detail.getAmount().intValue()*(detail.getnOneDiscount()==null? 0:detail.getnOneDiscount());
					linkeddetails1.add(row1);
				}
				tablesData.put("q", linkeddetails1);
				Map<String, String> textData = new HashMap<>();
				textData.put("a", contractInfo.getOrderUnit());
				textData.put("b", "");
				//textData.put("c", contractInfo.getProjectName());//项目名称对应使用单位
				textData.put("d", contractInfo.getDemanderCode());//demanderCode
				textData.put("j", contractInfo.getSupplierCode());
				textData.put("l", contractInfo.getScheduleDate()==null?"":DataConverter.toDateYMD(contractInfo.getScheduleDate()));
				textData.put("i", contractInfo.getGiveOutDate()==null?"":DataConverter.toDateYMD(contractInfo.getGiveOutDate()));
				textData.put("n", number+"");
				textData.put("o", df.format(sum)+"");
				
				textData.put("guaranteeMonths", "24");
				data.put("textData", textData);
				data.put("tablesData", tablesData);
				filename = DocService.genTemplate("重庆水泵厂有限责任公司_成套处.docx", data, "备件合同排产、装箱机发运单");
			}else{
				for (ExdeTbOPPlanTaskDetailReplace detail : details) {
					row1 = new ArrayList<>();
					row1.add((++order1) + "");
					row1.add(detail.getDeviceName());
					row1.add(detail.getType());
					row1.add(detail.getUnit());
					row1.add(detail.getAmount()+"");
					row1.add((detail.getnOneDiscount()==null? df.format(0):df.format(detail.getnOneDiscount())) + "");
					row1.add(df.format(detail.getAmount().intValue()*(detail.getnOneDiscount()==null? 0:detail.getnOneDiscount())) + "");
					//row1.add(df.format(detail.getnOneDiscount())+"");
					//row1.add(df.format(detail.getAmount()*detail.getnOneDiscount())+"");
					
					//row1.add(df.format(detail.getnOneDiscount())+"");
					//row1.add(df.format(detail.getPrice())+"");
					row1.add(detail.getMemo());
					number += detail.getAmount();
					sum += detail.getAmount().intValue()*(detail.getnOneDiscount()==null? 0:detail.getnOneDiscount());
					linkeddetails1.add(row1);
				}
				tablesData.put("q", linkeddetails1);
				Map<String, String> textData = new HashMap<>();
				textData.put("a", contractInfo.getOrderUnit());
				textData.put("b", contractInfo.getOrderDelegate()+" "+contractInfo.getOrderPhone());
				textData.put("c", contractInfo.getProjectName());//项目名称对应使用单位
				textData.put("d", contractInfo.getDemanderCode());
				textData.put("e", contractInfo.getOrderAddress());
				textData.put("f", contractInfo.getStop());
				textData.put("g", contractInfo.getOrderZip());
				textData.put("h", contractInfo.getOrderUnit());//开票单位
				textData.put("i", contractInfo.getTaxNumber());
				textData.put("j", contractInfo.getSupplierCode());
				textData.put("k", exdeTbOPPlanTask.getUser().getEmpLogin().getName());
				textData.put("l", contractInfo.getScheduleDate()==null?"":DataConverter.toDateYMD(contractInfo.getScheduleDate()));
				textData.put("m", exdeTbOPPlanTask.getdDeliveryDate()==null?"":DataConverter.toDateYMD(exdeTbOPPlanTask.getdDeliveryDate()));
				
				textData.put("n", number+"");
				textData.put("o", df.format(sum)+"");
				textData.put("p", exdeTbOPPlanTask.getUser().getSaleArea().getSuperior());
				
				textData.put("guaranteeMonths", "24");
				data.put("textData", textData);
				data.put("tablesData", tablesData);
				filename = DocService.genTemplate("备件合同排产、装箱机发运单.docx", data, "备件合同排产、装箱机发运单");
			}
			
			exdeTbOPPlanTask.setnPrintCount(exdeTbOPPlanTask.getnPrintCount()+1);
			exdeTbOPPlanTask.setnPrintDate(new Date());
		}
		return filename;
	}

	@Override
	public int updateExdeTbOPPlanTask(String[] ids, User user) {
		int result = 0;
		boolean t = true;
		//Pageable pageable = new PageRequest(0 / Integer.MAX_VALUE, Integer.MAX_VALUE, Sort.Direction.DESC, "createTime");
		for (String id : ids){
			ExdeTbOPPlanTask exdeTbOPPlanTask = exdeSchedulingRepository.findOne(id);
			if(exdeTbOPPlanTask == null){
				return result = 0;
			}
			ContractInfo old = contractService.getRepository().getDateThreeContractById(exdeTbOPPlanTask.getContractInfo().getContractId());
			List<ExdeTbOPPlanTaskDetail> exdeTbOPPlanTaskDetails = exdeSchedulingRepository.getPlanTaskDetail(id, new PageRequest(0 / Integer.MAX_VALUE, Integer.MAX_VALUE, Sort.Direction.DESC, "createTime"));
			List<ExdeTbOPPlanTaskDetailReplace> exdeTbOPPlanTaskDetailReplaces = exdeSchedulingRepository.getPlanTaskDetailReplace(id, new PageRequest(0 / Integer.MAX_VALUE, Integer.MAX_VALUE, Sort.Direction.ASC, "id"));
			List<QuoteDevice> quoteDevices = contractService.getDevices(0, Integer.MAX_VALUE, exdeTbOPPlanTask.getContractInfo().getContractId(), null, null);
			List<QuoteReplacement> quoteReplacements = contractService.getReplacements(0, Integer.MAX_VALUE, exdeTbOPPlanTask.getContractInfo().getContractId(), null, null);
			//ExdeTbOPPlanTask exdeTbOPPlanTask = new ExdeTbOPPlanTask();
			//exdeTbOPPlanTask.setId(PlanTaskId);
			//exdeTbOPPlanTask.setcPlanNumber(this.getPlanNumber());
			exdeTbOPPlanTask.setdOrderDate(old.getSignedDate());//订货日期
			exdeTbOPPlanTask.setdDeliveryDate(old.getGiveOutDate());//交货日期
			if(old.getDemanderCode()!=null&&!old.getDemanderCode().equals("")){
				exdeTbOPPlanTask.setcContractNumber(old.getSupplierCode()+"/"+old.getDemanderCode());//供方合同号
			}else{
				exdeTbOPPlanTask.setcContractNumber(old.getSupplierCode());//供方合同号
			}
			exdeTbOPPlanTask.setDemanderCode(old.getDemanderCode());//需方合同编号
			exdeTbOPPlanTask.setContractInfo(old);//合同ID
			exdeTbOPPlanTask.setContractType(old.getContractType());
			exdeTbOPPlanTask.setcUserUnit(old.getOrderUnit());//订货单位
			exdeTbOPPlanTask.setnUserUnitId(old.getCustomerId());//订货单位ID
			exdeTbOPPlanTask.setnContractManager(old.getSignOfficer());//合同签订人
			//exdeTbOPPlanTask.setcType("成套");
			//exdeTbOPPlanTask.setcState("新增");
			//exdeTbOPPlanTask.setcIsGenerated("未生成");//商品计划
			//exdeTbOPPlanTask.setUser(user);//创建人
			//exdeTbOPPlanTask.setUsername(user.getName());//创建人
			//exdeTbOPPlanTask.setdCreateDate(new Date());//创建时间
			//exdeTbOPPlanTask.setcCreateDept(user.getSaleArea().getSuperior());//创建部门
			//exdeTbOPPlanTask.setAreaName(user.getSaleArea().getAreaName());//创建片区
			exdeSchedulingRepository.save(exdeTbOPPlanTask);
			if(exdeTbOPPlanTaskDetails.size()>0){
				for(ExdeTbOPPlanTaskDetail exdeTbOPPlanTaskDetail : exdeTbOPPlanTaskDetails){
					exdeTbOPPlanTaskDetailRepository.delete(exdeTbOPPlanTaskDetail);
				}
				if(quoteDevices.size() == 0 && quoteReplacements.size()>0){
					ExdeTbOPPlanTaskDetail exdeTbOPPlanTaskDetail = new ExdeTbOPPlanTaskDetail();
					exdeTbOPPlanTaskDetail.setId(java.util.UUID.randomUUID().toString());
					exdeTbOPPlanTaskDetail.setUser(user);
					exdeTbOPPlanTaskDetail.setcCreateUser(user.getName());
					exdeTbOPPlanTaskDetail.setcCreateDept(user.getSaleArea().getSuperior());
					exdeTbOPPlanTaskDetail.setOpPlanTaskId(exdeTbOPPlanTask.getId());
					exdeTbOPPlanTaskDetail.setcProductModel("备件");
					exdeTbOPPlanTaskDetail.setcProductType("备件");
					exdeTbOPPlanTaskDetail.setnSinglePrice((float)old.getTotalSum());
					exdeTbOPPlanTaskDetail.setnCount(1);
					exdeTbOPPlanTaskDetail.setnTotalPrice(old.getTotalSum());
					//exdeTbOPPlanTaskDetail.setcAdditionClaim(quoteDevice);附加要求
					exdeTbOPPlanTaskDetail.setnContractProductId(old.getContractId());
					exdeTbOPPlanTaskDetail.setcProductName("备件");
					exdeTbOPPlanTaskDetail.setdGiveDate(old.getGiveOutDate());
					//exdeTbOPPlanTaskDetail.setCreateTime(new Date());
					exdeTbOPPlanTaskDetail.setdGiveDate(old.getGiveOutDate());
					exdeTbOPPlanTaskDetail.setdOrderDate(old.getSignedDate());
					exdeTbOPPlanTaskDetailRepository.save(exdeTbOPPlanTaskDetail);
				}
				if (quoteDevices.size() > 0){
					for(QuoteDevice quoteDevice : quoteDevices){
						ExdeTbOPPlanTaskDetail exdeTbOPPlanTaskDetail = new ExdeTbOPPlanTaskDetail();
						exdeTbOPPlanTaskDetail.setId(quoteDevice.getId());
						exdeTbOPPlanTaskDetail.setUser(user);
						exdeTbOPPlanTaskDetail.setcCreateUser(user.getName());
						exdeTbOPPlanTaskDetail.setcCreateDept(user.getSaleArea().getSuperior());
						exdeTbOPPlanTaskDetail.setOpPlanTaskId(exdeTbOPPlanTask.getId());
						exdeTbOPPlanTaskDetail.setcProductModel(quoteDevice.getProductModel());
						exdeTbOPPlanTaskDetail.setcProductType(quoteDevice.getProductType());
						exdeTbOPPlanTaskDetail.setnSinglePrice(quoteDevice.getUnitPrice());
						exdeTbOPPlanTaskDetail.setnCount(quoteDevice.getNumber());
						exdeTbOPPlanTaskDetail.setnTotalPrice((double)(quoteDevice.getNumber()*quoteDevice.getUnitPrice()));
						exdeTbOPPlanTaskDetail.setcAdditionClaim(quoteDevice.getcAttachment());//附加要求
						exdeTbOPPlanTaskDetail.setnContractProductId(old.getContractId());
						exdeTbOPPlanTaskDetail.setcMotor(quoteDevice.getcMotor());
						exdeTbOPPlanTaskDetail.setcPower(quoteDevice.getPower());
						exdeTbOPPlanTaskDetail.setcBitNumber(quoteDevice.getcBitNumber());
						//exdeTbOPPlanTaskDetail.setcUnit(quoteDevice.getcUnit());
						exdeTbOPPlanTaskDetail.setcFlow(quoteDevice.getFlux());
						exdeTbOPPlanTaskDetail.setcHead(quoteDevice.getPumpLift());
						exdeTbOPPlanTaskDetail.setcTemperature(quoteDevice.getTemperature());
						exdeTbOPPlanTaskDetail.setcViscosity(quoteDevice.getViscosity());
						exdeTbOPPlanTaskDetail.setcProportion(quoteDevice.getProportion());
						exdeTbOPPlanTaskDetail.setcInletPressure(quoteDevice.getInPressure());
						exdeTbOPPlanTaskDetail.setcOutletPressure(quoteDevice.getcOutletPressure());
						exdeTbOPPlanTaskDetail.setcMaterialFlow(quoteDevice.getFlowMaterial());
						exdeTbOPPlanTaskDetail.setcNPSHa(quoteDevice.getEffectiveNPSHA());
						exdeTbOPPlanTaskDetail.setcNPSHr(quoteDevice.getMustMPSHA());
						exdeTbOPPlanTaskDetail.setcProductName(quoteDevice.getProductName());
						exdeTbOPPlanTaskDetail.setdGiveDate(quoteDevice.getdDeliveryDate()==null ? old.getGiveOutDate() : quoteDevice.getdDeliveryDate());
						exdeTbOPPlanTaskDetail.setdOrderDate(old.getSignedDate());
						exdeTbOPPlanTaskDetail.setcTransMedium(quoteDevice.getTransMedia());
						exdeTbOPPlanTaskDetailRepository.save(exdeTbOPPlanTaskDetail);
					}
				}
			}
			if(quoteReplacements.size()>0){
				for(ExdeTbOPPlanTaskDetailReplace entity : exdeTbOPPlanTaskDetailReplaces){
					exdeTbOPPlanTaskDetailReplaceRepository.delete(entity);
				}
				for(QuoteReplacement quoteReplacement : quoteReplacements){
					ExdeTbOPPlanTaskDetailReplace ExdeTbOPPlanTaskDetailReplace = new ExdeTbOPPlanTaskDetailReplace();
					ExdeTbOPPlanTaskDetailReplace.setOpPlanTaskId(exdeTbOPPlanTask.getId());
					ExdeTbOPPlanTaskDetailReplace.setContractID(quoteReplacement.getContractID());
					ExdeTbOPPlanTaskDetailReplace.setContractType(quoteReplacement.getContractType());
					ExdeTbOPPlanTaskDetailReplace.setSupplierCode(quoteReplacement.getSupplierCode());
					ExdeTbOPPlanTaskDetailReplace.setDeviceName(quoteReplacement.getDeviceName());
					ExdeTbOPPlanTaskDetailReplace.setAmount(quoteReplacement.getAmount());
					ExdeTbOPPlanTaskDetailReplace.setMaterial(quoteReplacement.getMaterial());
					ExdeTbOPPlanTaskDetailReplace.setUnit(quoteReplacement.getUnit());
					ExdeTbOPPlanTaskDetailReplace.setPrice(quoteReplacement.getCostPrice());
					ExdeTbOPPlanTaskDetailReplace.setCostPrice(quoteReplacement.getCostPrice());
					ExdeTbOPPlanTaskDetailReplace.setDiscount(quoteReplacement.getDiscount());
					ExdeTbOPPlanTaskDetailReplace.setnOneDiscount(quoteReplacement.getnOneDiscount());
					ExdeTbOPPlanTaskDetailReplace.setType(quoteReplacement.getType());
					ExdeTbOPPlanTaskDetailReplace.setHostType(quoteReplacement.getHostType());
					ExdeTbOPPlanTaskDetailReplace.setMemo(quoteReplacement.getMemo());
					ExdeTbOPPlanTaskDetailReplace.setCreateTime(new Date());
					ExdeTbOPPlanTaskDetailReplace.setdGiveDate(old.getGiveOutDate());
					ExdeTbOPPlanTaskDetailReplace.setdOrderDate(old.getSignedDate());
					ExdeTbOPPlanTaskDetailReplace.setMaterialCoding(quoteReplacement.getMaterialCoding());
					exdeTbOPPlanTaskDetailReplaceRepository.save(ExdeTbOPPlanTaskDetailReplace);
				}
			}
			result = 1;
		}
		return result;
	}
}


















